package com.zjdiepu.www.manage.api.yw;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.net.SocketTimeoutException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.CheckEstimateResultStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.lang.HttpClientException;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.ibiz.third.IJuheAreaService;
import com.zjdiepu.www.ibiz.third.IJuheBrandService;
import com.zjdiepu.www.ibiz.third.IJuheCarService;
import com.zjdiepu.www.ibiz.third.IJuheCityService;
import com.zjdiepu.www.ibiz.third.IJuheProvinceService;
import com.zjdiepu.www.ibiz.third.IJuheSeriesService;
import com.zjdiepu.www.ibiz.third.net.IUsedCarExactEstimationService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessCarAreaPriceService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessService;
import com.zjdiepu.www.model.third.dto.JuheArea;
import com.zjdiepu.www.model.third.dto.JuheBrand;
import com.zjdiepu.www.model.third.dto.JuheCar;
import com.zjdiepu.www.model.third.dto.JuheCity;
import com.zjdiepu.www.model.third.dto.JuheProvince;
import com.zjdiepu.www.model.third.dto.JuheSeries;
import com.zjdiepu.www.model.third.ext.JuheAreaExt;
import com.zjdiepu.www.model.third.ext.JuheBrandExt;
import com.zjdiepu.www.model.third.ext.JuheCarExt;
import com.zjdiepu.www.model.third.ext.JuheCityExt;
import com.zjdiepu.www.model.third.ext.JuheProvinceExt;
import com.zjdiepu.www.model.third.ext.JuheSeriesExt;
import com.zjdiepu.www.model.third.request.juhe.JuheExactEstimationRequest;
import com.zjdiepu.www.model.third.response.juhe.JuheExactEstimationResponse;
import com.zjdiepu.www.model.yw.dto.YwBusinessCarAreaPrice;
import com.zjdiepu.www.model.yw.ext.YwBusinessCarAreaPriceExt;

/**
 * 二手车区域估价Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年04月24日 14时43分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "YwBusinessCarAreaPriceController", produces="application/json;charset=UTF-8")
@Api(tags = {"二手车区域估价"}, produces="application/json;charset=UTF-8")
public class YwBusinessCarAreaPriceController extends BaseController {
	@Resource(name="juheUsedCarExactEstimationServiceImpl")
	protected IUsedCarExactEstimationService<JuheExactEstimationResponse, JuheExactEstimationRequest> juheUsedCarExactEstimationService;
	@Resource
	private IJuheProvinceService juheProvinceService;
    @Resource
    private IJuheCityService juheCityService;
    @Resource
    private IJuheAreaService juheAreaService;
    @Resource
    private IJuheBrandService juheBrandService;
	@Resource
	private IJuheSeriesService juheSeriesService;
	@Resource
	private IJuheCarService juheCarService;
    @Resource
    private IYwBusinessCarAreaPriceService ywBusinessCarAreaPriceService;
    @Resource
    private IYwBusinessService ywBusinessService;
    
    /**
	 * @author xiongxiaotun <br/>
	 * @Title: selectBrands  <br/>
	 * @Description: 获取品牌  <br/>
	 * @param brandId
	 * @return
	 * @version V1.0  <br/>
	 */
	@ApiOperation(value = "获取品牌", response = Map.class, httpMethod="POST")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "brandId", value = "品牌ID", paramType="query", required = true, example="22"),
	})
	@RequestMapping(value = "selectBrands", method = { RequestMethod.POST })
	public ApiResponse selectBrands(String brandId) {
		Map<String,Map<Object, Object>> result = new HashMap<String, Map<Object,Object>>();
		//车品牌
		Map<Object, Object> juheBrands_ = new LinkedHashMap<Object, Object>();
		List<JuheBrand> juheBrands = null;
		JuheBrandExt juheBrandsExt = new JuheBrandExt();
		juheBrandsExt.withOutPage();
		juheBrandsExt.setOrderSql("`BIG_PPNAME` ASC");
		juheBrandsExt.setBaseWhere();
		juheBrands = juheBrandService.selectByExt(juheBrandsExt);
		if(CollectionUtils.isNotEmpty(juheBrands)) {
			for(JuheBrand juheBrand : juheBrands) {
				juheBrands_.put(juheBrand.getThirdId(), juheBrand.getBigPpname());
			}
		}
		result.put("juheBrands", juheBrands_);
		return ApiResponse.success(result);
	}
	
    /**
	 * @author xiongxiaotun <br/>
	 * @Title: selectSeries  <br/>
	 * @Description: 获取品牌车系  <br/>
	 * @param provinceId
	 * @return
	 * @version V1.0  <br/>
	 */
	@ApiOperation(value = "获取品牌车系", response = Map.class, httpMethod="POST")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "brandId", value = "品牌ID", paramType="query", required = true, example="22"),
		@ApiImplicitParam(name = "xlid", value = "系列ID", paramType="query", required = false, example="22")
	})
	@RequestMapping(value = "selectSeries", method = { RequestMethod.POST })
	public ApiResponse selectSeries(String brandId, String xlid) {
		if (StringUtils.isBlank(brandId)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
		}
		Map<String,Map<Object, Object>> result = new HashMap<String, Map<Object,Object>>();
		//车系
		Map<Object, Object> juheSeries_ = new LinkedHashMap<Object, Object>();
		List<JuheSeries> juheSeries = null;
		JuheSeriesExt juheSeriesExt = new JuheSeriesExt();
		juheSeriesExt.withOutPage();
		juheSeriesExt.setOrderSql("`XLNAME` ASC");
		juheSeriesExt.setBrandId(brandId);
		juheSeriesExt.setBaseWhere();
		juheSeries = juheSeriesService.selectByExt(juheSeriesExt);
		if(CollectionUtils.isNotEmpty(juheSeries)) {
			for(JuheSeries juheSery : juheSeries) {
				juheSeries_.put(juheSery.getXlid(), juheSery.getXlname());
			}
		}
		result.put("juheSeries", juheSeries_);
		
		//车型
		Map<Object, Object> juheCars_ = new LinkedHashMap<Object, Object>();
		if(CollectionUtils.isNotEmpty(juheSeries)) {
			if(StringUtils.isBlank(xlid)){
				xlid = juheSeries.get(0).getXlid();
			}
			JuheCarExt juheCarExt = new JuheCarExt();
			juheCarExt.withOutPage();
			juheCarExt.setOrderSql("CONVERT(`CAR_ID`, UNSIGNED) ASC");
			juheCarExt.setSeriesId(xlid);
			juheCarExt.setDpStatus(DpStatus.NORMAL.getCode());
			List<JuheCar> juheCars = juheCarService.selectByExt(juheCarExt);
			if(CollectionUtils.isNotEmpty(juheCars)) {
				for(JuheCar juheCar : juheCars) {
					juheCars_.put(juheCar.getCarId(), juheCar.getCxname());
				}
			}
		}
		result.put("juheCars", juheCars_);
		return ApiResponse.success(result);
	}
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: selectCars  <br/>
	 * @Description: 获取车系车型  <br/>
	 * @param provinceId
	 * @return
	 * @version V1.0  <br/>
	 */
	@ApiOperation(value = "获取车系车型", response = Map.class, httpMethod="POST")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "xlid", value = "车系ID", paramType="query", required = true, example="22"),
	})
	@RequestMapping(value = "selectCars", method = { RequestMethod.POST })
	public ApiResponse selectCars(String xlid) {
		if (StringUtils.isBlank(xlid)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
		}
		//车型
		Map<Object, Object> juheCars_ = new LinkedHashMap<Object, Object>();
		JuheCarExt juheCarExt = new JuheCarExt();
		juheCarExt.withOutPage();
		juheCarExt.setOrderSql("`CXNAME` ASC");
		juheCarExt.setSeriesId(xlid);
		juheCarExt.setDpStatus(DpStatus.NORMAL.getCode());
		List<JuheCar> juheCars = juheCarService.selectByExt(juheCarExt);
		if(CollectionUtils.isNotEmpty(juheCars)) {
			for(JuheCar juheCar : juheCars) {
				juheCars_.put(juheCar.getCarId(), juheCar.getCxname());
			}
		}
		return ApiResponse.success(juheCars_);
	}
	/**
     * @author xiongxiaotun <br/>
     * @Title: selectProvinces  <br/>
     * @Description: 获取省份  <br/>
     * @param provinceId
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "获取省份", response = Map.class, httpMethod="POST")
   	@RequestMapping(value = "selectProvinces", method = { RequestMethod.POST })
   	public ApiResponse selectCities() {
		JuheProvinceExt juheProvinceExt= new JuheProvinceExt();
		juheProvinceExt.withOutPage();
		juheProvinceExt.setBaseWhere();
		juheProvinceExt.setOrderSql("CONVERT(`REGION_CODE`, UNSIGNED) ASC");
		List<JuheProvince> juheProvinces = juheProvinceService.selectByExt(juheProvinceExt);
		Map<Object, Object> juheProvinces_ = new LinkedHashMap<Object, Object>();
		if(CollectionUtils.isNotEmpty(juheProvinces)) {
			for(JuheProvince juheProvince : juheProvinces) {
				juheProvinces_.put(juheProvince.getProId(), juheProvince.getProName());
			}
		}
		return ApiResponse.success(juheProvinces_);
   	}
	/**
     * @author xiongxiaotun <br/>
     * @Title: selectCities  <br/>
     * @Description: 获取省份城市  <br/>
     * @param provinceId
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "获取省份城市", response = Map.class, httpMethod="POST")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "provinceId", value = "省份ID", paramType="query", required = true, example="22"),
    })
   	@RequestMapping(value = "selectCities", method = { RequestMethod.POST })
   	public ApiResponse selectCities(String provinceId) {
		if (StringUtils.isBlank(provinceId)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
		}
		JuheCityExt juheCityExt= new JuheCityExt();
		juheCityExt.setProId(provinceId);
		juheCityExt.withOutPage();
		juheCityExt.setBaseWhere();
		juheCityExt.setOrderSql("CONVERT(`REGION_CODE`, UNSIGNED) ASC");
		List<JuheCity> cities = juheCityService.selectByExt(juheCityExt);
		Map<Object, Object> cities_ = new LinkedHashMap<Object, Object>();
		if(CollectionUtils.isNotEmpty(cities)) {
			for(JuheCity juheCity : cities) {
				cities_.put(juheCity.getCityId(), juheCity.getCityName());
			}
		}
		return ApiResponse.success(cities_);
   	}
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: selectAreas  <br/>
     * @Description: 获取城市区市  <br/>
     * @param cityId
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "获取城市区市", response = Map.class, httpMethod="POST")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "cityId", value = "省份ID", paramType="query", required = true, example="22"),
    })
   	@RequestMapping(value = "selectAreas", method = { RequestMethod.POST })
   	public ApiResponse selectAreas(String cityId) {
		if (StringUtils.isBlank(cityId)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
		}
		JuheAreaExt juheAreaExt= new JuheAreaExt();
		juheAreaExt.setCityId(cityId);
		juheAreaExt.withOutPage();
		juheAreaExt.setBaseWhere();
		juheAreaExt.setOrderSql("CONVERT(`REGION_CODE`, UNSIGNED) ASC");
		List<JuheArea> areas = juheAreaService.selectByExt(juheAreaExt);
		Map<Object, Object> areas_ = new LinkedHashMap<Object, Object>();
		if(CollectionUtils.isNotEmpty(areas)) {
			for(JuheArea juheArea : areas) {
				areas_.put(juheArea.getAreaId(), juheArea.getAreaName());
			}
		}
		return ApiResponse.success(areas_);
   	}
    
    /**
   	 * @author xiongxiaotun <br/>
   	 * @Title: estimate  <br/>
   	 * @Description: 聚合数据：二手车接口：估值<br/>
   	 * @param request
   	 * @return
   	 * @version V1.0  <br/>
   	 * @throws HttpClientException 
   	 * @throws SocketTimeoutException 
   	 */
       @ApiOperation(value = "精确估价", response = YwBusinessCarAreaPrice.class, httpMethod="POST")
   	@RequestMapping(value = "estimate", method = { RequestMethod.POST })
   	public ApiResponse estimate(@Validated @ModelAttribute JuheExactEstimationRequest request) {
       	AbstractSysUser currentUser = getCurrentUser();
   		return ywBusinessService.saveYwBusinessCarAreaPrice(request, currentUser);
   	}
    
    /**
   	 * @author xiongxiaotun <br/>
   	 * @Title: queryProvince  <br/>
   	 * @Description: 确认估价情况<br/>
   	 * @param request
   	 * @return
   	 * @version V1.0  <br/>
   	 * @throws HttpClientException 
   	 * @throws SocketTimeoutException 
   	 */
       @ApiOperation(value = "确认估价情况", response = Boolean.class, httpMethod="POST")
   	@RequestMapping(value = "checkIfNeedEstimate", method = { RequestMethod.POST })
   	public ApiResponse checkIfNeedEstimate(@Validated @ModelAttribute JuheExactEstimationRequest request) {
   		CheckEstimateResultStatus checkIfNeedEstimate = ywBusinessService.checkIfNeedEstimate(request);
   		if(CheckEstimateResultStatus.YI_GU_JIA.equals(checkIfNeedEstimate)) {
   			return ApiResponse.success(true);
   		} else if(CheckEstimateResultStatus.CHONG_XIN_GU_JIA.equals(checkIfNeedEstimate)){
   			return ApiResponse.fail(ResultFlagType.ESTIMATE_HAS_CHANGED);
   		} else {
   			return ApiResponse.fail(ResultFlagType.ESTIMATE_NOT_EXECUTE);
   		}
   	}

    /**
     * @author xiongxiaotun <br/>
     * @Title: save  <br/>
     * @Description: 新增二手车区域估价 <br/>
     * @param ywBusinessCarAreaPrice
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增二手车区域估价", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute YwBusinessCarAreaPrice ywBusinessCarAreaPrice) {
    	AbstractSysUser currentUser = getCurrentUser();
    	ywBusinessCarAreaPrice.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywBusinessCarAreaPrice.setModifierName(currentUser.getName());
        ywBusinessCarAreaPriceService.saveUpdateAndDelete(ywBusinessCarAreaPrice, OperateType.add);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: remove  <br/>
     * @Description: 删除二手车区域估价<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除二手车区域估价", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywBusinessCarAreaPriceService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: disable  <br/>
     * @Description: 禁用二手车区域估价<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用二手车区域估价", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywBusinessCarAreaPriceService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: enable <br/>
     * @Description: 启用二手车区域估价<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用二手车区域估价", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywBusinessCarAreaPriceService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: modify  <br/>
     * @Description: 修改二手车区域估价 <br/>
     * @param ywBusinessCarAreaPrice
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改二手车区域估价", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute YwBusinessCarAreaPrice ywBusinessCarAreaPrice) {
    	AbstractSysUser currentUser = getCurrentUser();
    	ywBusinessCarAreaPrice.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywBusinessCarAreaPrice.setModifierName(currentUser.getName());
    	ywBusinessCarAreaPriceService.saveUpdateAndDelete(ywBusinessCarAreaPrice, OperateType.edit);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询二手车区域估价<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询二手车区域估价", response = YwBusinessCarAreaPrice.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       YwBusinessCarAreaPrice ywBusinessCarAreaPrice = ywBusinessCarAreaPriceService.selectById(id);
       if(null == ywBusinessCarAreaPrice) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(ywBusinessCarAreaPrice);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询二手车区域估价 <br/>
     * @param ywBusinessCarAreaPriceExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询二手车区域估价",response = YwBusinessCarAreaPrice.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute YwBusinessCarAreaPriceExt ywBusinessCarAreaPriceExt){
        ywBusinessCarAreaPriceExt.notDeleted();
        PageVo page = getPage(ywBusinessCarAreaPriceExt);
        int records = ywBusinessCarAreaPriceService.countByExt(ywBusinessCarAreaPriceExt);
        page.setRecords(records);
        if (records > 0) {
            List<YwBusinessCarAreaPrice> dpBaseDataDictionaries = ywBusinessCarAreaPriceService.selectByExt(ywBusinessCarAreaPriceExt);
            page.setRows(dpBaseDataDictionaries);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }

}
